<template>
  <el-dialog
    title="添加用户"
    :visible.sync="dialogVisible"
    class="user-add-container"
  >
    <el-form
      ref="createForm"
      :model="formData"
      label-width="200px"
      :show-message="false"
    >
      <el-form-item
        label="账号"
        prop="name"
        required
      >
        <el-tooltip
          class="el-tooltip"
          content="用户的账号，仅支持英文和数字"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-input
          v-model.trim="formData.name"
          auto-complete="off"
          placeholder="请输入账号"
          class="input"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="用户名"
        prop="displayName"
      >
        <el-tooltip
          class="el-tooltip"
          content="用户的显示名称"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-input
          v-model="formData.displayName"
          auto-complete="off"
          placeholder="请输入用户名"
          class="input"
        ></el-input>
      </el-form-item>
      <el-form-item
        class="password-form-item"
        label="密码"
        prop="password"
        required
      >
        <el-tooltip
          class="el-tooltip"
          content="用户密码（不得少于6位）"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-input
          :type="passwordType"
          v-model.trim="formData.password"
          autocomplete="new-password"
          placeholder="请输入密码"
          class="input"
        >
        </el-input>
        <svg-icon
          icon-class="eye-close"
          v-if="passwordType ==='password'"
          @click="showPassword"
        ></svg-icon>
        <svg-icon
          icon-class="eye"
          v-else
          @click="hiddePassword"
        ></svg-icon>
      </el-form-item>
      <el-form-item
        label="
          角色"
        prop="roleUuidList"
        required
      >
        <el-tooltip
          class="el-tooltip"
          content="选择用户所属的角色"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-select
          v-model="formData.roleUuidList"
          placeholder="请选择角色"
          multiple
          class="select"
        >
          <el-option
            v-for="item in roleList"
            :key="item.uuid"
            :label="item.description"
            :value="item.uuid"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="邮箱"
        prop="email"
      >
        <el-tooltip
          class="el-tooltip"
          content="用户邮箱地址"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-input
          v-model.trim="formData.email"
          auto-complete="off"
          placeholder="请输入邮箱"
          class="input"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="手机号"
        prop="mobile"
      >
        <el-tooltip
          class="el-tooltip"
          content="用户手机号码"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-input
          v-model.trim="formData.mobile"
          auto-complete="off"
          placeholder="请输入手机号"
          class="input"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="可切换组织"
        prop="organizationIdList"
        required
      >
        <el-tooltip
          class="el-tooltip"
          content="代表用户可以选择的组织"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-cascader
          ref="cascader"
          v-model="organizationIdList"
          :options="organizationList"
          :props="{label:'name',value:'id',multiple:true,checkStrictly:true,emitPath:false}"
          clearable
          class="input"
          @change="onOrganizationIdListChange"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item
        label="岗位"
        prop="jobId"
        required
      >
        <el-tooltip
          class="el-tooltip"
          content="根据当前户所属的组织选择目前所从事的岗位"
          effect="light"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-select
          v-model="formData.jobId"
          placeholder="请选择岗位"
          class="select"
        >
          <el-option
            v-for="item in organizationSelectList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="addUser"
        :loading="btnLoading"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '../../../api/role';
import { parseError } from '../../../utils';
import { Message } from 'element-ui';
import { validateCreateForm } from './service';
import * as md5 from 'md5';
import { createUserApi } from '../../../api/user';
import { getOrganizationListApi } from '../../../api/organization';

export default {
  props: {
    organizationList: {
      type: Array,
      default: () => []
    },
    organizationTotalList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      passwordType: 'password',
      roleList: [],
      dialogVisible: false,
      formData: {
        name: '',
        displayName: '',
        password: '',
        roleUuidList: [],
        mobile: '',
        email: '',
        organizationIdList: [],
        jobId: ''
      },
      btnLoading: false,
      organizationIdList: []
    };
  },
  computed: {
    organizationSelectList() {
      return this.organizationTotalList.filter(item => this.formData.organizationIdList.includes(item.id));
    }
  },
  watch: {
    dialogVisible: {
      handler(value) {
        if (!value) {
          this.$refs.createForm.resetFields();
          this.organizationIdList = [];
        }
      }
    }
  },
  methods: {
    showDialog() {
      getRoleListApi()
        .then(res => (this.roleList = res))
        .catch(error => Message.error(parseError(error)));
      this.dialogVisible = true;
    },
    addUser() {
      const validError = validateCreateForm(this.formData);
      if (validError) return Message.warning(validError);
      let jobId;
      if (this.formData.organizationIdList.length > 0) jobId = this.formData.organizationIdList[0];
      this.btnLoading = true;
      createUserApi(
        this.formData.name,
        this.formData.displayName,
        md5(this.formData.password),
        jobId,
        this.formData.organizationIdList,
        this.formData.roleUuidList,
        true,
        this.formData.email,
        this.formData.mobile
      )
        .then(res => {
          this.dialogVisible = false;
          this.$emit('search');
          Message.success('创建用户成功');
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.btnLoading = false));
    },
    onOrganizationIdListChange(selectedList) {
      let newIdList = selectedList.filter(id => !this.formData.organizationIdList.includes(id));
      let oldIdList = this.formData.organizationIdList.filter(id => !selectedList.includes(id));
      const organizationList = this.$refs.cascader.getCheckedNodes(false);
      if (newIdList.length > 0) {
        const organizationIdList = this.treeToList(organizationList.filter(item => newIdList.includes(item.value))).map(item => item.value);
        this.organizationIdList = this.formData.organizationIdList.concat(organizationIdList);
      }
      if (oldIdList.length > 0) {
        const sortOrganizationList = organizationList.sort((a, b) => b.level - a.level);
        sortOrganizationList.forEach(organization => {
          if (organization.hasChildren && !organization.children.find(child => child.checked)) organization.checked = false;
        });
        const organizationIdList = sortOrganizationList.filter(item => !item.hasChildren || item.children.find(child => child.checked)).map(item => item.value);
        this.organizationIdList = organizationIdList;
      }
      this.formData.organizationIdList = this.organizationIdList;
    },
    treeToList(list) {
      let result = [];
      const fn = list => {
        list.forEach(item => {
          result.push(item);
          item.hasChildren ? fn(item.children) : '';
        });
      };
      fn(list);
      return result;
    },
    showPassword() {
      this.passwordType = 'text';
    },
    hiddePassword() {
      this.passwordType = 'password';
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tooltip {
  margin-right: 10px;
}
.user-add-container {
  .input {
    width: 300px;
  }
  .select {
    width: 300px;
  }
  .password-form-item {
    position: relative;
    .svg-icon {
      top: 12px;
      left: 265px;
      position: absolute;
      padding-left: 10px;
    }
  }
}
</style>
<style lang="scss">
.user-add-container {
  .el-tag__close {
    display: none !important;
  }
}
</style>
